package com.expertria.glex.xhr;

 

public class JSONRequest {
	public static int counter = 0;
	 
	private Object keyObject ;
	private Object response;
	
	public Object getKeyObject() {
		return keyObject;
	}

	public void setKeyObject(Object keyObject) {
		this.keyObject = keyObject;
	}

	public Object getResponse() {
		return response;
	}
	
	void setResponse(Object response) {
		this.response = response;
	}
	
	public synchronized static AsyncToken  get( String url )
	{
		return  get( url,new Object());
	}
	public synchronized static AsyncToken  get( String url, Object keyObject)
	{
		++counter;
		AsyncToken handler = new AsyncToken() ;
		
		String callbackName = "JSONCallback" + counter +handler.hashCode();
		JSONRequest rq=  new JSONRequest();
		rq.setKeyObject(keyObject);
		rq.get( url+callbackName, callbackName, handler );
	
		return handler;
	}	
	
	 
	
	private  synchronized void get( String url, String callbackName, AsyncToken handler  )
	{
		 
		createCallbackFunction( handler, callbackName , this );
		addScript(url);
	}
	private static native void addScript(String url) /*-{
	
	 
	  var scr = document.createElement("script");
	  scr.setAttribute("language", "JavaScript");
	  scr.setAttribute("src", url);
	  scr.setAttribute("charset", "UTF-8");
	  document.getElementsByTagName("body")[0].appendChild(scr);
	}-*/;
	
	private native static void createCallbackFunction( IJSONResponder obj, String callbackName  , JSONRequest r)/*-{
		tmpcallback = function( j ){
			obj.@com.expertria.glex.xhr.IJSONResponder::onRequestComplete(Lcom/google/gwt/core/client/JavaScriptObject;Lcom/expertria/glex/xhr/JSONRequest;)( j , r);
		};
		eval( "window."+callbackName+"=tmpcallback" );
	}-*/;
}
